package com.tzu.ft.ui.comps;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.TransferHandler;

/** 文件拖拽监听 */
public class FileDragAndDropHandler extends TransferHandler {

	private static final long serialVersionUID = 1L;

	private DragAndDropExecute dragAndDrop;

	public FileDragAndDropHandler(DragAndDropExecute dragAndDrop) {
		this.dragAndDrop = dragAndDrop;
	}

	@Override
	public boolean importData(JComponent comp, Transferable t) {
		try {

			List<File> filelist = new ArrayList<File>();

			DataFlavor[] dataFlavors = t.getTransferDataFlavors();
			for (DataFlavor dataFlavor : dataFlavors) {
				Object obj = t.getTransferData(dataFlavor);
				if (obj instanceof List) {
					List<Object> list = (List<Object>) obj;
					for (Object file : list) {
						if (file instanceof File) {
							filelist.add((File) file);
						}
					}
				} else {
					if (obj instanceof File) {
						filelist.add((File) obj);
					}
				}
			}

			Object o = t.getTransferData(DataFlavor.javaFileListFlavor);

			String filepath = o.toString();
			if (filepath.startsWith("[")) {
				filepath = filepath.substring(1);
			}
			if (filepath.endsWith("]")) {
				filepath = filepath.substring(0, filepath.length() - 1);
			}
			// 转为数组
			File[] objlist = filelist.toArray(new File[filelist.size()]);

			// 返回处理
			dragAndDrop.execute(objlist);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean canImport(JComponent comp, DataFlavor[] flavors) {
		for (int i = 0; i < flavors.length; i++) {
			if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {
				return true;
			}
		}
		return false;
	}

	public static interface DragAndDropExecute {
		void execute(File[] filelist);
	}

}
